
/**
 * 组件参数说明
 *    list 列表数据
 *    currentPage 当前页
 *    loadCountPage 共多少页
 *    clientHeight 容器内渲染内容的高
 *    setList(page=请求当前的页数) {}  下拉/上拉
 */
import React, { Component, Fragment } from 'react';
import { ListView, PullToRefresh } from "antd-mobile";
import NotEmptys from "../not-emptys/not-emptys";
const PSIZE = 10;
const dataSource = new ListView.DataSource({
  rowHasChanged: (row1, row2) => row1 !== row2,
});

class ListViews extends Component {

  constructor(props) {
    super(props)
    this.state = {
      list: props.list || [], // 列表
      currentPage: props.currentPage || 1, // 当前页
      loadCountPage: props.loadCountPage || 1,   // 一共有多少页
      isLoading: false,    // 上拉加载更多的状态
      refreshing: false,  // 下拉加载的动态
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      list: nextProps.list,
      currentPage: nextProps.currentPage,
      loadCountPage: nextProps.loadCountPage
    })
  }

  // 下拉刷新
  onRefresh = () => {
    setTimeout(() => {
      this.setState({
        refreshing: true,
        list: [],
      }, () => {
        this.props.setList(1);
        this.setState({ refreshing: false });
      });
    }, 1000)
  }

  // 上拉加载更多
  onEndReached = async () => {
    const { currentPage, isLoading, loadCountPage } = this.state;
    // 记载中
    if (isLoading) return
    // 判断还有没有下一页
    if (loadCountPage > currentPage) {
      this.setState({
        currentPage: currentPage + 1,
        isLoading: true,
      })
      await this.props.setList(currentPage + 1);
      this.setState({ isLoading: false })
    }
  }

  render() {

    const { list, isLoading, refreshing, loadCountPage, currentPage } = this.state;
    const clientHeight = this.props.clientHeight || "100vh";

    return (
      <div className="list-view">
        {
          list.length>0? <Fragment>
            {
              !refreshing? <ListView  dataSource={dataSource.cloneWithRows(list)} ref="home"
                renderFooter={() => (<div style={{ paddingBottom: 15, textAlign: 'center' }}>
                  {isLoading ? '加载中...' : loadCountPage===currentPage? '我是有底线的～' : ''}
                </div>)}
                renderRow={this.props.renderRow}
                style={{
                  height: clientHeight,
                  overflow: 'auto',
                }}
                pageSize={PSIZE}
                onEndReached={this.onEndReached}
                pullToRefresh={
                  <PullToRefresh
                    distanceToRefresh={100}
                    refreshing={refreshing}
                    onRefresh={() => this.onRefresh()}
                  />
                }
              /> : <p></p>
            }
          </Fragment>: <NotEmptys />
        }
        
      </div>  
    )
  }
}

export default ListViews;

